package com.igelato.service;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.igelato.config.TencentAccessPolicy;
import com.igelato.controller.AdminUser.*;
import com.igelato.mapper.AdminAuthMapper;
import com.igelato.mapper.AdminRoleMapper;
import com.igelato.mapper.AdminUserMapper;
import com.igelato.model.AdminAuth;
import com.igelato.model.AdminRole;
import com.igelato.model.AdminUser;
import com.igelato.response.AppException;
import com.igelato.response.ErrorCodeMsgEnum;
import com.igelato.utils.ThreadLocalTool;
import com.igelato.utils.Tools;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sts.v20180813.StsClient;
import com.tencentcloudapi.sts.v20180813.models.GetFederationTokenRequest;
import com.tencentcloudapi.sts.v20180813.models.GetFederationTokenResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

/**
 * @TableName: admin_user
 * @Description:
 * @Author: wht
 * @Date: 2023-12-30
 */

@Slf4j
@Service
public class AdminUserService extends ServiceImpl<AdminUserMapper, AdminUser> {
    @Autowired
    AdminUserMapper adminUserMapper;
    @Autowired
    AdminRoleMapper adminRoleMapper;

    @Autowired
    AdminAuthMapper adminAuthMapper;

    // 自己 ---------------------------------------------
    public AdminUser loginByPwd(LoginByPwdDto loginDto) {
        LambdaQueryWrapper<AdminUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdminUser::getMobile, loginDto.getMobile());
        AdminUser adminUser = adminUserMapper.selectOne(queryWrapper);

        if (adminUser == null) {
            throw new AppException(ErrorCodeMsgEnum.LOGIN_ERROR);
        }
        String password = Tools.encryptPassword(loginDto.getPassword());
        if (!adminUser.getPassword().equals(password)) {
            throw new AppException(ErrorCodeMsgEnum.LOGIN_ERROR);
        }

        return adminUser;
    }

    public Boolean resetMyPwd(ResetMyPwdDto resetMyPwdDto) {
        AdminUser user = ThreadLocalTool.getUser();
        String pwdDB = user.getPassword();
        String pwdOld = Tools.encryptPassword(resetMyPwdDto.getOld_pwd());


        if (!pwdDB.equals(pwdOld)) {
            throw new AppException(ErrorCodeMsgEnum.LOGIN_ERROR);
        }

//        更新---------------------
        AdminUser adminUser = new AdminUser();
        adminUser.setId(user.getId());
        adminUser.setPassword(Tools.encryptPassword(resetMyPwdDto.getNew_pwd()));

        int res = adminUserMapper.updateById(adminUser);
        return res > 0;
    }

//    public Boolean updateMyInfo(UpdateMyInfoDto updateMyInfoDto) {
//        AdminUser adminUser = new AdminUser();
//        adminUser.setId(ThreadLocalTool.getUser().getId());
//        adminUser.setMobile(updateMyInfoDto.getMobile());
//        adminUser.setTrue_name(updateMyInfoDto.getTrue_name());
//
//        int res = adminUserMapper.updateById(adminUser);
//        return res > 0;
//    }

    public HashMap getCosTempToken() {
        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
            // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
            Properties properties = new Properties();
            File configFile = new File("tencentYun.properties");
            properties.load(new FileInputStream(configFile));

            Credential cred = new Credential(properties.getProperty("SecretId"), properties.getProperty("SecretKey"));
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("sts.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);

            // 实例化要请求产品的client对象,clientProfile是可选的
            StsClient client = new StsClient(cred, properties.getProperty("Region"), clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            GetFederationTokenRequest req = new GetFederationTokenRequest();
            req.setName("GetFederationToken");

//            设置策略 -----------------------------
            // 创建访问策略对象
            TencentAccessPolicy accessPolicy = new TencentAccessPolicy();
            accessPolicy.setVersion(properties.getProperty("Version"));

            TencentAccessPolicy.Statement statement = new TencentAccessPolicy.Statement();
            statement.setEffect("allow");
            statement.setAction(properties.getProperty("Action").split(","));
//            设置Resource
            ArrayList<String> resourceArr = new ArrayList<>();
            for (String path : properties.getProperty("Path").split(",")) {
                resourceArr.add("qcs::cos:" + properties.getProperty("Region") + ":uid/" + properties.getProperty("Uid") + ":" + properties.getProperty("BucketName") + "/" + path);
            }
            statement.setResource(resourceArr.toArray(new String[0]));

            accessPolicy.setStatement(new TencentAccessPolicy.Statement[]{statement});

            // 使用FastJSON将访问策略对象转换为JSON字符串
            String policyJson = JSON.toJSONString(accessPolicy);

            System.out.println(policyJson);

            req.setPolicy(policyJson);
            // 返回的resp是一个GetFederationTokenResponse的实例，与请求对象对应
            GetFederationTokenResponse resp = client.GetFederationToken(req);

            HashMap res = new HashMap();
            res.put("TmpSecretId", resp.getCredentials().getTmpSecretId());
            res.put("TmpSecretKey", resp.getCredentials().getTmpSecretKey());
            res.put("SecurityToken", resp.getCredentials().getToken());
//            res.put("StartTime", Math.floor(ThreadLocalTool.getTime() / 1000));
            res.put("ExpiredTime", resp.getExpiredTime());
            return res;
        } catch (Exception e) {
            throw new AppException(ErrorCodeMsgEnum.WX_COS_ERROR);
        }
    }

    // 员工 -------------------------------------------------
    public Boolean resetOnePwd(Integer admin_user_id) {
        AdminUser adminUser = new AdminUser();
        adminUser.setId(admin_user_id);
        adminUser.setPassword(Tools.getInitPwd());

        int res = adminUserMapper.updateById(adminUser);
        return res > 0;
    }

    public HashMap<String, Object> getResAdminUser(AdminUser adminUser) {
        ArrayList<String> auth_list = new ArrayList<>();
        if (adminUser.getRole_ids() != null) {
            LambdaQueryWrapper<AdminRole> queryWrapperRole = new LambdaQueryWrapper<>();
            queryWrapperRole.in(AdminRole::getId, adminUser.getRole_ids());

            List<AdminRole> adminRoles = adminRoleMapper.selectList(queryWrapperRole);
            for (AdminRole adminRole : adminRoles) {
                LambdaQueryWrapper<AdminAuth> queryWrapperAuth = new LambdaQueryWrapper<>();
                queryWrapperAuth.in(AdminAuth::getId, adminRole.getAuth_ids());
                List<AdminAuth> adminAuths = adminAuthMapper.selectList(queryWrapperAuth);
                for (AdminAuth adminAuth : adminAuths) {
                    auth_list.add(adminAuth.getName_en());
                }
            }
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("mobile", adminUser.getMobile());
        map.put("true_name", adminUser.getTrue_name());
        map.put("auth_list", auth_list);
        return map;
    }
}
